package com.mzkj.wanjulaile.mobile.api.modules.toy.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mzkj.common.data.StatusCode;
import com.mzkj.common.utils.Collections3;
import com.mzkj.common.utils.DateUtils;
import com.mzkj.common.utils.StringUtils;
import com.mzkj.wanjulaile.mobile.api.common.controller.BaseController;
import com.mzkj.wanjulaile.mobile.api.common.entity.ResultEntity;
import com.mzkj.wanjulaile.mobile.api.modules.account.entity.Account;
import com.mzkj.wanjulaile.mobile.api.modules.account.entity.Baby;
import com.mzkj.wanjulaile.mobile.api.modules.account.service.AccountService;
import com.mzkj.wanjulaile.mobile.api.modules.account.service.BabyService;
import com.mzkj.wanjulaile.mobile.api.modules.appointment.entity.AppointmentCollection;
import com.mzkj.wanjulaile.mobile.api.modules.appointment.service.AppointmentCollectionService;
import com.mzkj.wanjulaile.mobile.api.modules.brand.entity.Brand;
import com.mzkj.wanjulaile.mobile.api.modules.brand.service.BrandService;
import com.mzkj.wanjulaile.mobile.api.modules.category.entity.ProductCategory;
import com.mzkj.wanjulaile.mobile.api.modules.category.entity.SubCategory;
import com.mzkj.wanjulaile.mobile.api.modules.category.service.ProductCategoryService;
import com.mzkj.wanjulaile.mobile.api.modules.category.service.SubCategoryService;
import com.mzkj.wanjulaile.mobile.api.modules.session.entity.Session;
import com.mzkj.wanjulaile.mobile.api.modules.session.service.SessionService;
import com.mzkj.wanjulaile.mobile.api.modules.shoppingCart.entity.ShoppingCart;
import com.mzkj.wanjulaile.mobile.api.modules.shoppingCart.service.ShoppingCartService;
import com.mzkj.wanjulaile.mobile.api.modules.toy.entity.Image;
import com.mzkj.wanjulaile.mobile.api.modules.toy.entity.Toy;
import com.mzkj.wanjulaile.mobile.api.modules.toy.service.ImageService;
import com.mzkj.wanjulaile.mobile.api.modules.toy.service.ToyService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(value = "toy")
public class ToyController extends BaseController {
    @Autowired
    private ToyService toyService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @Autowired
    private SubCategoryService subCategoryService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private AppointmentCollectionService appointmentCollectionService;
    @Autowired
    private ImageService imageService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private BabyService babyService;
    @Autowired
    private SessionService sessionService;
    @Value("${pageSize}")
    private Integer pageSize;

    @Value("${maxPageSize}")
    private Integer maxPageSize;

    //品牌首字母
    private static final String[] CAPITAL_ARR = {"2", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    //获取筛选数据
    @RequestMapping(value = "getFilterData")
    @ResponseBody
    public ResultEntity<Map> getFilterData() {
        ResultEntity<Map> result = new ResultEntity<Map>();
        Map<String, Object> map = Maps.newHashMap();
        List<Map> brandList = Lists.newArrayList();
        try {
            List<Brand> brands = brandService.findListByCapital();
            for (int i = 0; i < CAPITAL_ARR.length; i++) {
                List<Brand> capList = new ArrayList<Brand>();
                Map<String, Object> capMap = Maps.newHashMap();
                for (Brand brand : brands) {
                    if (brand.getCapital().equals(CAPITAL_ARR[i])) {
                        capList.add(brand);
                    }
                }
                if (capList.size() > 0) {
                    capMap.put("capitalName", CAPITAL_ARR[i]);
                    capMap.put("brandCapList", capList);
                    brandList.add(capMap);
                }
            }
            List<Brand> hotBrandList = brandService.getHotBrand(12);//前12个
            List<ProductCategory> productCategoryList = productCategoryService.getAllCategory();
            map.put("hotBrandList", hotBrandList);
            map.put("brandList", brandList);
            map.put("productCategoryList", productCategoryList);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
            result.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC4002.getValue());
            result.setMsg(StatusCode.SC4002.getDesc());
            result.setData(map);
        }
        return result;
    }

    /**
     * 条件查询玩具列表数据
     *
     * @param toy( ageStart:最小年龄,ageEnd:最大年龄,brands:品牌id,
     *                      sorts:排序id(1:默认排序,2:人气最高,3:最新上架),productCategorys:分类id,name:玩具名称)
     * @param currentPage 当前页数
     * @param pageNum  每页数据大小
     * @return
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public ResultEntity<Map<String,List>> list(Toy toy, Integer currentPage, String pageNum) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (!StringUtils.isEmpty(pageNum)) {
            if (Integer.valueOf(pageNum) > maxPageSize) {
                pageSize = maxPageSize;
            } else {
                pageSize = Integer.valueOf(pageNum);
            }
        }
        logger.debug("------------- page=" + currentPage + " -------------");
        //设置每次请求获取条数
        Map<String, String> pageMap = Maps.newHashMap();
        pageMap.put("limit", "limit " + (currentPage - 1) * pageSize + "," + pageSize);
        toy.setSqlMap(pageMap);
        ResultEntity<Map<String,List>> result = new ResultEntity<>();
        Map<String,List> map=Maps.newHashMap();
        List<String> subCateList = Lists.newArrayList();
        try {
            if (!StringUtils.isEmpty(toy.getType())) {
                SubCategory subCategory = new SubCategory();
                subCategory.setType(Integer.valueOf(toy.getType()));
                List<SubCategory> subCategoryList = subCategoryService.getSubCategoryByType(subCategory);
                for (SubCategory sub : subCategoryList) {
                    subCateList.add(sub.getId());
                }
                map.put("subCategprys", subCateList);
            }
            String prductCategorys = toy.getProductCategorys();
            if (prductCategorys != null && prductCategorys.length() > 0) {
                String[] categoryArr = prductCategorys.split(",");
                subCateList.addAll(Arrays.asList(categoryArr));
            }
            toy.setSubCategoryIdList(subCateList);
            List<Toy> toyList = toyService.getHomeToyList(toy);

            if (!Collections3.isEmpty(toyList)) {
                result.setStatusCode(StatusCode.SC0.getValue());
                result.setMsg(StatusCode.SC0.getDesc());
            } else {
                //没有更多
                result.setStatusCode(StatusCode.SC1000.getValue());
                result.setMsg(StatusCode.SC1000.getDesc());
            }
            map.put("toyList",toyList);
            result.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC4002.getValue());
            result.setMsg("获取数据失败");
            result.setData(null);
        }
        return result;
    }

    /**
     *查询玩具详情
     * @param id    玩具id
     * @param accessToken
     * @return
     */
    @RequestMapping(value = "viewDetail")
    @ResponseBody
    public ResultEntity<Map<String,Object>> viewDetail( String id, String accessToken) {
        ResultEntity<Map<String,Object>> result = new ResultEntity<>();
        Map<String, Object> map = Maps.newHashMap();
        Account account = null;
        Toy t;
        Toy toy=toyService.get(id);
        Image image = new Image();
        Image instruction = new Image();
        List<String> paramList = Lists.newArrayList();
        int shoppingCartCount = 0;
        try {
            t = toyService.getById(toy);
            if (t != null && !StringUtils.isEmpty(t.getParams())) {
                String[] parArr = t.getParams().split(",");
                for (String str : parArr) {
                    if (!StringUtils.isEmpty(str)) {
                        paramList.add(StringEscapeUtils.unescapeHtml4(str));
                    }
                }
                t.setParamList(paramList);
            }
            if (!StringUtils.isEmpty(accessToken)) {
                Session session = sessionService.findByAccessToken(accessToken);
                if(session != null){
                    account = accountService.get2(session.getAccountId());
                    if(account != null){
                        List<ShoppingCart> shoppingCartList = shoppingCartService.findList2ByAccountId(account.getId());
                        if (!Collections3.isEmpty(shoppingCartList)) {
                            shoppingCartCount = shoppingCartList.size();
                        }
                    }
                }
            }
            //查询视屏
            image.setToy(toy);
            image = imageService.getVedioByToyId(image);
            AppointmentCollection appointmentCollection = new AppointmentCollection();
            List<AppointmentCollection> appList = new ArrayList<>();
            List<AppointmentCollection> appList1 = new ArrayList<>();
            if (account != null) {
                appointmentCollection.setType("0");
                appointmentCollection.setToy(toy);
                appointmentCollection.setAccount(account);
                appList = appointmentCollectionService.getExists(appointmentCollection);
                appointmentCollection.setType("1");
                appList1 = appointmentCollectionService.getExists(appointmentCollection);
            }
            //查询说明书
            instruction.setToy(toy);
            List<Image> instructionList = imageService.getInstructions(instruction);
            t.setDetails(StringEscapeUtils.unescapeHtml4(t.getDetails()));
            map.put("toy", t);
            map.put("vedio", image);
            map.put("shoppingCartCount", shoppingCartCount);
            map.put("existCollection", appList.size() > 0 ? true : false);
            map.put("existAppoint", appList1.size() > 0 ? true : false);
            map.put("existInstruction", instructionList.size() > 0 ? true : false);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
            result.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatusCode(StatusCode.SC4002.getValue());
            result.setMsg(StatusCode.SC4002.getDesc());
        }
        return result;
    }

    /**
     * 获取首页数据
     *
     * @return ResultMessage<Map>
     */
    @RequestMapping("/getHomeDate")
    @ResponseBody
    public ResultEntity<Map> getNewProduct() {
        ResultEntity<Map> result = new ResultEntity<Map>();
        Map<String, List> map = Maps.newHashMap();
        try {
            Toy toy = new Toy();
            toy.setSorts("3");//新品上架
            int pageSize = 9;
            Map<String, String> pageMap = Maps.newHashMap();
            pageMap.put("limit", "limit 0 , " + pageSize);
            toy.setSqlMap(pageMap);
            List<Toy> newProductList = toyService.getHomeToyList(toy);
            //热门玩具
            Toy hotToy = new Toy();
            hotToy.setSorts("2"); //热门
            int hotPageSize = 6;
            Map<String, String> hotPageMap = Maps.newHashMap();
            hotPageMap.put("limit", "limit 0 , " + hotPageSize);
            hotToy.setSqlMap(hotPageMap);
            List<Toy> hotProductList = toyService.getHomeToyList(hotToy);
            List<Brand> brandlist = brandService.getHotBrand(12);//前12个
            map.put("newProductList", newProductList);
            map.put("hotBrandList", brandlist);
            map.put("hotProductList", hotProductList);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg("");
            result.setData(map);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setStatusCode(StatusCode.SC4002.getValue());
            result.setMsg("获取数据失败");
        }
        return result;
    }

    @RequestMapping("/getToysBurgInfo")
    @ResponseBody
    public ResultEntity<Map> getToysBurgInfo() {
        ResultEntity<Map> result = new ResultEntity<Map>();
        SubCategory subCategory = new SubCategory();
        Map<String, String> pageMap = Maps.newHashMap();
        pageMap.put("limit", "limit 0,15");//前15个
        subCategory.setSqlMap(pageMap);
//        Page<SubCategory> page = new Page<SubCategory>(1, 15);//前15个
//        subCategory.setPage(page);
        List<Brand> brandList;
        List<SubCategory> toyTypeList;
        try {
            brandList = brandService.getHotBrand(12);//前12个
            toyTypeList = subCategoryService.findPage(subCategory);
            Map<String, List> map = Maps.newHashMap();
            map.put("brandList", brandList);
            map.put("toyTypeList", toyTypeList);
            result.setStatusCode(StatusCode.SC0.getValue());
            result.setMsg(StatusCode.SC0.getDesc());
            result.setData(map);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.setStatusCode(StatusCode.SC4002.getValue());
            result.setMsg(StatusCode.SC4002.getDesc());
        }
        return result;
    }
}